package cn.stacey.spring.ssm.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stacey.spring.ssm.domain.Post;
import cn.stacey.spring.ssm.service.PostService;

@Controller
public class RestPostController {
	@Autowired
	PostService service;
	
	@RequestMapping(path="/posts",method=RequestMethod.GET)
	@ResponseBody   //返回json数据
	public List<Post> list(){
		return service.findAll();
	}
	
	//通过id查文章
	@RequestMapping(path="/posts/{id}",method=RequestMethod.GET)
	@ResponseBody   //返回json数据
	public Post FindById(@PathVariable("id") int id){
		return service.getById(id);
	}
	
	//通过id 删除文章
	@RequestMapping(path="/deleteposts/{id}",method=RequestMethod.DELETE)
	@ResponseBody   //返回json数据
	public Map<String,Object> deleteById(@PathVariable("id") int id){
		service.deleteById(id);
		Map<String,Object> result=new HashMap<>();
		result.put("code", 1);
		result.put("success", true);
		result.put("message", "删除成功！");
		return result;
	}
//有问题，一直提示	Duplicate entry '***' for key **
//	@RequestMapping(path="/posts/{id}",method=RequestMethod.PUT)
//	@ResponseBody   //返回json数据
//	public Map<String,Object> update(@PathVariable("id") int id,Post p){
//		service.update(id,p);
//		Map<String,Object> result=new HashMap<>();
//		result.put("code", 1);
//		result.put("success", true);
//		result.put("message", "更新成功！");
//		return result;
//	}
	
	@RequestMapping("/posts/ajax")
	public String ajax() {
		return "ajax";
	}
}
